﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DMS.Logic;
using System.IO;

namespace WebUI.Document
{
	/// <summary>
	/// Summary description for $codebehindclassname$
	/// </summary>
	public class Download : IHttpHandler
	{

		public void ProcessRequest(HttpContext context)
		{
			int documentId = 0;
			if (context.Request.QueryString["docid"] == null)
				return;

			context.Response.Buffer = true;

			documentId = int.Parse(context.Request.QueryString["docid"]);

			DMS.DAL.Document doc = BL.getInstance().GetDocumentById(documentId);
			byte[] data = BL.getInstance().GetDocumentData(documentId);

			
			context.Response.AppendHeader("content-disposition","attachment; filename=" + doc.Name);
			context.Response.AppendHeader("content-length", data.Length.ToString());

			context.Response.ContentType = MapContentType(doc.OriginalFileName);
			context.Response.OutputStream.Write(data, 0, data.Length);


			
		}

		private string MapContentType(string fileName)
		{
			string ext = Path.GetExtension(fileName);
			string type="";

			if (ext != null)
			{
				switch (ext.ToLower())
				{
					case ".htm":
					case ".html":
						type = "text/HTML";
						break;

					case ".txt":
						type = "text/plain";
						break;

					case ".doc":
					case ".rtf":
						type = "application/msword";
						break;
					case ".pdf":
						type="application/pdf";
						break;

					case ".csv":
					case ".xls":
						type = "application/x-msexcel";
						break;
					case ".png":
					case ".tiff":
					case ".gif":
						type = "image/" + ext.ToLower();
						break;
					case ".jpg":
						type = "image/jpeg";
						break;

					case ".mp4":
					case ".ogg":
						type = "video/" + ext.ToLower();
						break;
		
					case ".mp3":
						type = "audio/mpeg";
						break;



				}
			}

			return type;


		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}
